<template>
  <div class="addOrEditForm">
    <h4>{{$t('configLazyLoad.channel.enterpriseTip8')}}</h4>
    <span class="tip">{{$t('configLazyLoad.channel.wexinTip112')}}</span>
    <el-form class="form" ref="ruleForm" :rules="rules" :model="form"  label-position="left" label-width="160px">
      <el-form-item :label="$t('configLazyLoad.channel.enterpriseTip9')" prop="name">
        <el-input v-model.trim="form.name" :disabled="showAddOrEditType === 'edit'"></el-input>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.channel.enterpriseTip10')" prop="agentid">
        <el-input v-model.trim="form.agentid" :disabled="showAddOrEditType === 'edit'"></el-input>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.channel.enterpriseTip11')" prop="secret">
        <el-input v-model.trim="form.secret" :disabled="showAddOrEditType === 'edit'"></el-input>
      </el-form-item>
      <el-form-item :label="$t('configLazyLoad.channel.enterpriseTip12')" prop="corpid">
        <el-input v-model.trim="form.corpid" :disabled="showAddOrEditType === 'edit'"></el-input>
        <question-tooltip
          class="wechatPlatformTooltip"
          :direction="'bottom'"
          :tipContent="$t('configLazyLoad.channel.enterpriseTip13')">
        </question-tooltip>
      </el-form-item>
      <!-- 日程接入 -->
      <!-- <el-form-item :label="$t('configLazyLoad.channel.useSche')">
        <el-radio-group v-model.trim="form.scheduleEnable">
          <el-radio :label="false">{{$t('configLazyLoad.public.noReuse')}}</el-radio>
          <el-radio :label="true">{{$t('configLazyLoad.public.reuse')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <p class="remark" style="margin-bottom: 5px">{{$t('configLazyLoad.channel.wexinTip23')}}</p> -->
      <!-- 消息分发技能组 -->
      <el-form-item :label="$t('config.channel.msgToPeer')" prop="to_peer">
        <el-select size="mini" filterable v-model.trim="form.to_peer" :placeholder="$t('public.pleasePick')">
          <el-option
            v-for="(item, index) in peerOptions"
            :key="index"
            :label="item.DisplayName"
            :value="item.Exten">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 启用智能机器人 -->
      <el-form-item :label="$t('config.channel.isUseRobt')" prop="robot">
        <el-select size="mini" filterable v-model.trim="form.robot" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
          <el-option value="">{{$t('public.pleasePick')}}</el-option>
          <el-option
            v-for="item in allrobotOptions"
            :key="item._id"
            :label="item.robot_name_new"
            :disabled="item.disabled"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 机器人辅助座席 -->
      <el-form-item :label="$t('configLazyLoad.channel.robotAssistId')" prop="robotAssistId" v-show="aiRobots.length > 0">
        <el-select size="mini" filterable v-model.trim="form.robotAssistId" :placeholder="$t('public.pleasePick')" @visible-change="robotSelectShow">
          <el-option value="">{{$t('public.pleasePick')}}</el-option>
          <el-option
            v-for="item in aiRobots"
            :key="item._id"
            :label="item.robot_name_new"
            :disabled="item.disabled"
            :value="item._id">
          </el-option>
        </el-select>
      </el-form-item>
      <!-- 是否开启触发词命中转人工 -->
      <el-form-item :label="$t('configLazyLoad.channel.turnTip3')" prop="openTriggerWord" style="text-align: left">
        <el-radio-group v-model.trim="form.openTriggerWord">
          <el-radio :label="true">{{$t('public.yes')}}</el-radio>
          <el-radio :label="false">{{$t('public.no')}}</el-radio>
        </el-radio-group>
        <question-tooltip
                class="wechatPlatformTooltip"
                :direction="'bottom'"
                :tipContent="$t('configLazyLoad.channel.turnTip4')">
        </question-tooltip>
      </el-form-item>
      <!-- 转人工触发词 -->
      <el-form-item :label="$t('config.channel.userPeopleWord')" prop="convert_words">
        <el-input size="mini" v-model.trim="form.convert_words" :placeholder="$t('configLazyLoad.channel.turnTip5')"></el-input>
        <question-tooltip
                class="wechatPlatformTooltip"
                :direction="'bottom'"
                :tipContent="$t('configLazyLoad.channel.turnTip6')">
        </question-tooltip>
      </el-form-item>
      <el-form-item class="csrFormItem" :label="$t('config.channel.isUseSatisfaction2')" prop="webchat_csr">
        <el-radio class="radio statis-radio" v-model="form.webchat_csr" :label="true">{{$t('config.channel.enabled')}}</el-radio>
        <el-radio class="radio" v-model="form.webchat_csr" :label="false">{{$t('config.channel.notEnabled')}}</el-radio>
      </el-form-item>
      <!-- 欢迎语推送时机 -->
      <el-form-item style="text-align: left" :label="$t('config.channel.sendWelcomeMsg')" prop="welcomePushTime" >
        <el-radio-group v-model="form.welcomePushTime" @change="pushTimeChange">
          <el-radio class="radio" label="access">{{$t('config.channel.enterSystem')}}</el-radio>
          <el-radio class="radio" label="claim">{{$t('config.channel.collectSeats')}}</el-radio>
        </el-radio-group>
      </el-form-item>
      <!-- 欢迎语内容设置 -->
      <el-form-item style="text-align: left" :label="$t('config.channel.welcomeMsg')" prop="welcome_msg">
        <span class="remark">{{$t('configLazyLoad.channel.webStyleTip5')}}</span>
        <question-tooltip
          class="weiboTooltip"
          :direction="'bottom'"
          :tipContent="$t('configLazyLoad.channel.webStyleTip6')">
        </question-tooltip>
        <div class="placeholder_box">
          <dl v-for="place in placeholderArr" @click="addPlaceholder(place.data)" :title="place.content">
            {{place.content}}
            <i class="iconfont icon-zhankai"></i>
          </dl>
        </div>
        <el-input size="mini" type="textarea" v-model="form.welcome_msg"></el-input>
      </el-form-item>
    </el-form>
    <div v-if="showAddOrEditType === 'add'" class="btn">
      <el-button class="primary_btn" style="margin-right: 20px" @click="cancel()">{{$t('public.cancel')}}</el-button>
      <el-button type="primary" class="primary_btn" @click="nextStep()">{{$t('public.nextStep')}}</el-button>
    </div>
    <div v-if="showAddOrEditType === 'edit'" class="btn">
      <el-button class="primary_btn" style="margin-right: 20px" @click="cancel()">{{$t('public.cancel')}}</el-button>
      <el-button type="primary" class="primary_btn" @click="nextStep()">{{$t('public.save')}}</el-button>
    </div>
  </div>
</template>
<script>
import bus from '@/store/eventBus'
import questionTooltip from '@/components/ui-modules/questionToolTip/QuestionToolTip.vue'
import { deepClone, randomWord } from '@/utils/m7Utils'
export default {
  name: 'addOrEditForm',
  data () {
    return {
      rules: {
        name: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        agentid: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        secret: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
        corpid: [
          { required: true, message: this.$t('validate.required'), trigger: 'blur' }
        ],
      },
      form: {
        name: '',
        agentid: '',
        secret: '',
        corpid: '',
        // scheduleEnable: '',
        to_peer: '',
        robot: '',
        robotAssistId: '',
        welcomePushTime: 'access',
        welcome_msg: '',
        openTriggerWord: true,
        convert_words: '',
        webchat_csr: true
      },
      placeholderArr: [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ],
      aiRobots: [],
      allrobotOptions: [],
      peerOptions: []
    }
  },
  props: {
    showAddOrEditType: {
      type: String,
      default: () => {
        return 'add'
      }
    },
    formInitData: {
      type: Object,
      default: () => {
        return {}
      }
    },
    wechatUrl: {
      type: String,
      default: () => {
        return ''
      }
    }
  },
  components: {
    questionTooltip
  },
  methods: {
    robotSelectShow () {
      this.$store.dispatch('queryM7AIRobot', {}).then((res) => {
        if (res && res.success && res.data && res.data.length > 0) {
          let aiRobot = res.data
          let allRobot = this.allrobotOptions
          aiRobot.forEach((item1) => {
            item1._id = item1.Id
            item1.robot_name_new = item1.Nick
            let exist = allRobot.findIndex((all) => {
              return all.Id === item1.Id
            })
            if (exist === undefined) {
              allRobot.push(item1)
            } else {
              allRobot.splice(exist, 1, item1)
            }
          })
          this.aiRobots = aiRobot
          this.allrobotOptions = allRobot
        }
      })
    },
    nextStep () {
      if (!this.peerOptions.length) {
        this.$message.error(this.$t('configLazyLoad.channel.addSkillGroupTips'))
        return
      }
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          if (!this.form.to_peer ) {
            this.$message.error(this.$t('webchat.placeSkillsGrouop'))
            return
          }
          if (this.form.robot === '') {
            this.form.robotType = ''
          } else {
            this.allrobotOptions.forEach((item) => {
              if (item._id === this.form.robot) {
                if (item.Nick) {
                  this.form.robotType = item.robotType
                } else {
                  this.form.robotType = item.robot_type_new
                }
                this.form.robotname = item.robot_name_new
              }
            })
          }
//          机器人辅助座席，增加assistRobotType参数
          this.aiRobots.map((item) => {
            if (this.form.robotAssistId === item._id) {
              if (this.form.robotAssistId !== '') {
                this.$set(this.form, 'assistRobotType', item.robotType)
              } else {
                this.$set(this.form, 'assistRobotType', '')
              }
            }
          })
          if (this.showAddOrEditType === 'add') {
            let sendData = deepClone(this.form)
            sendData.token = randomWord(false, 32)
            sendData.encoding_AESKey = randomWord(false, 43)
            sendData.server_url = this.wechatUrl + '/wxEnterprise/' + sendData.corpid + sendData.agentid
            this.$store.dispatch('saveWxEnterpriseConfig', sendData).then(res => {
              if (res && res.success) {
                this.$message.success(this.$t('configLazyLoad.channel.addSucc'))
                this.$emit('devNextStep', sendData)
                bus.$emit('getTableData')
              }
            })
          } else {
            let sendData = deepClone(this.form)
            sendData._id = this.formInitData._id
            this.$store.dispatch('updateWxEnterpriseConfig', sendData).then(res => {
              if (res && res.success) {
                this.$message.success(this.$t('configLazyLoad.public.editSuccess'))
                bus.$emit('enterpriseUpdate')
                bus.$emit('getTableData')
              }
            })
          }
        }
      })
      // bus.$emit('getTableData')
    },
    //  更改欢迎语推送时机
    pushTimeChange (data) {
      if (data === 'access') {
        this.placeholderArr = [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }
        ]
        let str = deepClone(this.form.welcome_msg)
        str = str.replace(/\{agent\}/g, '')
        str = str.replace(/\{agentName\}/g, '')
        this.form.welcome_msg = str
      } else if (data === 'claim') {
        this.placeholderArr = [
          {
            content: this.$t('configLazyLoad.channel.nickName'),
            data: 'nickName'
          }, {
            content: this.$t('configLazyLoad.channel.agent'),
            data: 'agent'
          }, {
            content: this.$t('configLazyLoad.channel.agentName'),
            data: 'agentName'
          }, {
            content: this.$t('configLazyLoad.channel.agentNickName'),
            data: 'agentNickName'
          }, {
            content: this.$t('configLazyLoad.channel.agentPhone'),
            data: 'agentPhone'
          }
        ]
      }
    },
    // 添加欢迎语占位符
    addPlaceholder (data) {
      this.form.welcome_msg += '{' + data + '}'
    },
    cancel () {
      bus.$emit('enterpriseCancel')
    },
    getInitDataFun () {
      let form = deepClone(this.formInitData)
      this.form.name = form.name ? form.name : ''
      this.form.agentid = form.agentid ? form.agentid : ''
      this.form.welcomePushTime = form.welcomePushTime ? form.welcomePushTime : 'access'
      this.form.welcome_msg = form.welcome_msg ? form.welcome_msg : ''
      this.form.secret = form.secret ? form.secret : ''
      this.form.corpid = form.corpid ? form.corpid : ''
      this.form.to_peer = form.to_peer ? form.to_peer : ''
      this.form.robot = form.robot ? form.robot : ''
      this.form.robotAssistId = form.robotAssistId ? form.robotAssistId : ''
      this.form.convert_words = form.convert_words ? form.convert_words : ''
      this.form.openTriggerWord = this.openTriggerWord ? form.openTriggerWord : true
      this.form.webchat_csr = this.webchat_csr ? form.webchat_csr : true
      this.pushTimeChange(this.form.welcomePushTime)
    }
  },
  beforeMount () {
    let robotConfig = this.$store.dispatch('getCache', { type: 'robotConfig' }).then(req => {
      let robotConfig = this.$getCache('robotConfig') || []
      this.allrobotOptions = robotConfig
      this.$store.dispatch('queryM7AIRobot', {}).then((res) => {
        if (res && res.success && res.data && res.data.length > 0) {
          let aiRobot = res.data
          aiRobot.forEach((item) => {
            item._id = item.Id
            item.robot_name_new = item.Nick
          })
          this.aiRobots = aiRobot
          let configArr = []
          this.allrobotOptions.forEach((config) => {
            if (config.robot_type !== 'didi') {
              configArr.push(config)
            }
          })
          this.allrobotOptions = configArr.concat(this.aiRobots)
        }
      })
    })
    let mailQueues = this.$store.dispatch('getCache', { type: 'mailQueues' }).then(req => {
      let mailQueues = req
      this.peerOptions = mailQueues || []
    })
    Promise.all([robotConfig, mailQueues]).then(([rep1, rep2]) => {
      this.getInitDataFun()
    })
  }
}
</script>
<style lang="stylus" scoped>
  @import "../../../../../assets/common.styl"
  .addOrEditForm
    margin 30px auto
    width 540px
    .csrFormItem
      text-align left
    .btn
      margin 25px  
      text-align center
    h4
      text-align left
      margin-bottom 10px
    .tip
      color #3B5998
      font-size 12px
    .form
      margin-top 30px
      width 500px
    .wechatPlatformTooltip
      position absolute
      right -26px  
      
  .placeholder_box
    margin-top 10px
    font-size 12px
    line-height:16px
    dl
      border 1px solid $c-main
      color $c-main
      border-radius 6px
      display inline-block
      padding 4px
      margin 0 10px 10px 0
      cursor pointer
    .iconfont
      font-size 12px
  .remark
    color #3b5998
    font-size 12px
    .tip
      cursor pointer
      display inline-block
      height 16px
      width 16px
      border 1px solid $c-main
      text-align center
      line-height 16px
      border-radius 50%
      margin-left 2px
      .iconfont
        font-size 10px
        color $c-main
</style>
<style lang="stylus">
  .addOrEditForm .el-select
    width 100%
</style>


